import os
from io import BytesIO
import base64

from django.shortcuts import render
import pandas as pd
from django.conf import settings
import seaborn as sns
import matplotlib.pyplot as plt
from django.http import HttpResponse, JsonResponse


def index(request):
    sql = 'select * from parasite'
    df = pd.read_sql(sql, settings.ENGINE)
    # print(df)
    # print(df.dtypes)
    # 求sum的时候,因为有时间类型,这里会报错.
    df.set_index(keys='时间', inplace=True)
    df['总金额'] = df.sum(axis=1)
    # 新增一列年份
    # 还原时间为列
    df.reset_index(inplace=True)
    df.insert(loc=1, column='年份', value=df.时间.dt.year)
    df_sum = df.groupby(by='年份')[['总金额']].sum()
    sns.set()
    plt.rcParams['font.sans-serif'] = 'SimHei'
    plt.rcParams['axes.unicode_minus'] = False

    df.groupby(by='年份')[['总金额']].sum().plot(marker='o')
    _ = plt.xticks([2016, 2017, 2018])
    plt.ylabel('总金额')
    file_path = os.path.join(settings.BASE_DIR, 'static/img', 'trend.png')
    plt.savefig(file_path, dpi=300)
    plt.close()

    return render(request, 'parasite_market/index.html')


def trend(request):
    sql = 'select * from parasite'
    df = pd.read_sql(sql, settings.ENGINE)
    # print(df)
    # print(df.dtypes)
    # 求sum的时候,因为有时间类型,这里会报错.
    df.set_index(keys='时间', inplace=True)
    df['总金额'] = df.sum(axis=1)
    # 新增一列年份
    # 还原时间为列
    df.reset_index(inplace=True)
    df.insert(loc=1, column='年份', value=df.时间.dt.year)
    df_sum = df.groupby(by='年份')[['总金额']].sum()
    sns.set()
    plt.rcParams['font.sans-serif'] = 'SimHei'
    plt.rcParams['axes.unicode_minus'] = False

    df.groupby(by='年份')[['总金额']].sum().plot(marker='o')
    _ = plt.xticks([2016, 2017, 2018])
    plt.ylabel('总金额')
    file_path = os.path.join(settings.BASE_DIR, 'static/img', 'trend.png')
    plt.savefig(file_path, dpi=300)
    plt.close()

    sio = BytesIO()
    plt.savefig(sio, format='png', bbox_inches='tight',
                dpi=200)
    data = base64.encodebytes(sio.getvalue()).decode()  # 解码为base64编码的png图片数据
    src = 'data:image/png;base64,' + str(data)

    return JsonResponse({'src': src})
    # return HttpResponse(content=sio.getvalue(), content_type='image/png')
